<?php

namespace app\admin\controller;

use app\admin\service\UserService;
use app\BaseController;
use app\model\ConfigModel;
use app\model\DepartmentAdminModel;
use app\model\DepartmentLevelModel;
use app\model\DepartmentModel;
use app\model\LogModel;
use app\model\MessageModel;
use app\model\PushMessageModel;
use app\model\RoleModel;
use app\model\UnitModel;
use app\model\UserModel;
use app\socket\Server;
use think\App;
use think\facade\Queue;
use think\swoole\Websocket;

class Department extends BaseController 
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new DepartmentModel();
    }

    /**
     * 获取部门名称
     * @return bool|string
     */
    public function getName(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $UserService = new UserService($this->app);
            $data = $UserService->getNotDelDepartmentName($this->userData['unit_id'],$param['id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取当前学制
     * @return bool|string
     */
    public function levelModel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $info = $this->mode->field('id,mode,stage')->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!$info['mode']) throw new \Exception('当前部门为非学制部门！');
            $DepartmentLevelModel = new DepartmentLevelModel();
            return success([
                'id' => $info['mode'],
                'name' => $DepartmentLevelModel->where('id','=',$info['mode'])->value('name')
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 管理部门选择器
     * @return bool|string
     */
    public function adminDepartmentSelector(): bool|string
    {
        try {
            $where = [];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $data = $this->mode->where($where)
                ->withCount('users')
                ->select()->toArray();
            $data = buildTree($data);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 部门选择器
     * @return bool|string
     */
    public function selector(): bool|string
    {
        try {
            $where = [];
            if ($this->userData['role_id']) {
                $DepartmentAdminModel = new DepartmentAdminModel();
                $department_id = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->column('department_id');
                if (count($department_id)) {
                    $where[] = ['id', 'in', $department_id];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $data = $this->mode->where($where)
                ->withCount('users')
                ->withCount('departmentAdmins')
                ->select()->toArray();
            foreach ($data as &$item) {
                $getAllSubcategories = getAllSubcategories($data, $item['id']);
                $users_count = array_column($getAllSubcategories, 'users_count');
                $users_count = array_sum($users_count);
                $item['users_count'] = $item['users_count'] + $users_count;
            }
            $UnitModel = new UnitModel();
            $unit_name = $UnitModel->where('id', '=', $this->userData['unit_id'])->value('name');
            $list[] = [
                'id' => 0,
                'name' => $unit_name,
                'child' => buildTree($data)
            ];
            return success(['list' => $list, 'total' => count($data), 'name' => $unit_name]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 部门选择器
     * @return bool|string
     */
    public function selector3(): bool|string
    {
        try {
            $where = [];
            if ($this->userData['role_id']) {
                $DepartmentAdminModel = new DepartmentAdminModel();
                $department_id = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->column('department_id');
                if (count($department_id)) {
                    $where[] = ['id', 'in', $department_id];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $data = $this->mode->where($where)
                ->withCount('users')
                ->withCount('departmentAdmins')
                ->select()->toArray();
//            foreach ($data as &$item) {
//                $getAllSubcategories = getAllSubcategories($data, $item['id']);
//                $users_count = array_column($getAllSubcategories, 'users_count');
//                $users_count = array_sum($users_count);
//                $item['users_count'] = $item['users_count'] + $users_count;
//            }
            $UnitModel = new UnitModel();
            $unit_name = $UnitModel->where('id', '=', $this->userData['unit_id'])->value('name');
            $list[] = [
                'id' => 0,
                'name' => $unit_name,
                'child' => buildTree($data)
            ];
            return success(['list' => $list, 'total' => count($data), 'name' => $unit_name]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 部门选择器2
     * @return bool|string
     */
    public function selector2(): bool|string
    {
        try {
            $where = [];
            if ($this->userData['role_id']) {
                $DepartmentAdminModel = new DepartmentAdminModel();
                $department_id = $DepartmentAdminModel->where('uid', '=', $this->userData['id'])->column('department_id');
                if (count($department_id)) {
                    $where[] = ['id', 'in', $department_id];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $data = $this->mode->where($where)
                ->withCount('users')
                ->withCount('departmentAdmins')
                ->select()->toArray();
            foreach ($data as &$item) {
                $getAllSubcategories = getAllSubcategories($data, $item['id']);
                $users_count = array_column($getAllSubcategories, 'users_count');
                $users_count = array_sum($users_count);
                $item['users_count'] = $item['users_count'] + $users_count;
            }
            return success(buildTree($data));
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 指定部门管理员选项列表
     * @return false|string
     */
    public function adminUserList(): bool|string
    {
        try {
            $UserModel = new UserModel();
            $RoleModel = new RoleModel();
            $role_id = $RoleModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['mode', '=', 1]
            ])->value('id');
            $list = $UserModel->field('id,name')
                ->where([
                    'unit_id' => $this->userData['unit_id'],
                    'role_id' => $role_id
                ])->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function index(): bool|string
    {
        try {
            $where = [];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $data = $this->mode->where($where)
                ->withCount('users')
                ->withCount('departmentAdmins')
                ->select()->toArray();
            foreach ($data as &$item) {
                $getAllSubcategories = getAllSubcategories($data, $item['id']);
                $users_count = array_column($getAllSubcategories, 'users_count');
                $users_count = array_sum($users_count);
                $item['users_count'] = $item['users_count'] + $users_count;
            }
            $UnitModel = new UnitModel();
            $unit_name = $UnitModel->where('id', '=', $this->userData['unit_id'])->value('name');
            return success(['list' => buildTree($data), 'total' => count($data), 'name' => $unit_name]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 创建学制阶段
     * @param $pid
     * @param $mode
     * @return bool
     */
    public function CreateStage($pid,$mode): bool
    {
        try {
            $DepartmentLevelModel = new DepartmentLevelModel();
            $level_rules = $DepartmentLevelModel->where('id','=',$mode)->value('level_rules');
            $level_rules = json_decode($level_rules,true);
            $data = [];
            foreach ($level_rules as $key => $item) {
                $data[] = [
                    'unit_id' => $this->userData['unit_id'],
                    'pid' => $pid,
                    'level' => 2,
                    'name' => $item,
                    'type' => 2,
                    'mode' => $mode,
                    'stage' => $key,
                    'time' => time()
                ];
            }
            if (!empty($data)) {
                $DepartmentModel = new DepartmentModel();
                $DepartmentModel->insertAll($data);
            }
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    public function add2(): bool|string
    {
        try {
            $this->mode->startTrans();
            $param = $this->request->param();
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'department_management'
            ])->value('value') ?? '';
            $config = json_decode($config, true);
            $param['type'] = $config['type'];
            switch ($config['type']) {
                case 1:
                    //非学院
                    $this->validate($param, [
                        'name|部门名称'  =>  'require',
                    ]);
                    if ($this->mode->where([
                        ['unit_id', '=', $this->userData['unit_id']],
                        ['name', '=', $param['name']],
                        ['type', '=', $param['type']],
                        ['pid', '=', $param['pid']??0],
                    ])->value('id')) {
                        throw new \Exception('部门名称不可重复！');
                    }
                    if (!empty($param['pid'])) {
                        $pid = $this->mode->find($param['pid']);
                        if ($pid['level'] > 9) throw new \Exception('层级不能超过十级');
                        $level = $pid['level'] + 1;
                        $param['level'] = $level;
                    } else {
                        $param['level'] = 1;
                    }
                    $param['unit_id'] = $this->userData['unit_id'];
                    $param['time'] = time();
                    $this->mode->insert($param);
                    break;
                case 2:
                    //学院制
                    $this->validate($param, [
                        'name|部门名称'  =>  'require',
                        'mode|学制模板' =>  'require',
//                        'stage|学制阶段' =>  'require',
                    ]);
                    if ($this->mode->where([
                        ['unit_id', '=', $this->userData['unit_id']],
                        ['type', '=', $param['type']],
                        ['pid', '=', $param['pid']??0],
                        ['name', '=', $param['name']],
                    ])->value('id')) {
                        throw new \Exception('部门名称不可重复！');
                    }
                    if (!empty($param['pid'])) {
                        $pid = $this->mode->find($param['pid']);
                        if ($pid['level'] > 9) throw new \Exception('层级不能超过十级');
                        $level = $pid['level'] + 1;
                        //验证：如果是学院制，第三层级（班级）班级编号必填，且单位内不能重复
//                        if ($level == 3 && empty($param['number']) && $param['type'] == 2) throw new \Exception('缺少班级编号！');
                        $number = $this->mode->where([
                            ['unit_id','=', $this->userData['unit_id']],
                            ['pid','=',$param['pid']]
                        ])->column('number');
                        if (!empty($param['number']) && count($number) > 0 && in_array($param['number'], $number)) throw new \Exception('班级编号已存在！');
                        $param['level'] = $level;
                        $param['unit_id'] = $this->userData['unit_id'];
                        $param['time'] = time();
                        $this->mode->insert($param);
                    } else {
                        $param['level'] = 1;
                        $param['unit_id'] = $this->userData['unit_id'];
                        $param['time'] = time();
                        $pid = $this->mode->insertGetId([
                            'unit_id' => $this->userData['unit_id'],
                            'name' => $param['name'],
                            'type' => 2,
                            'mode' => $param['mode'],
                            'time' => time()
                        ]);
                        if (!$this->CreateStage($pid,$param['mode'])) throw new \Exception('学制阶段创建失败!');
                    }
                    break;
                default:
                    throw new \Exception('系统错误！');
            }
            $this->mode->commit();
            return success([], '添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function add(): bool|string
    {
        $param = $this->request->param();
        try {
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'department_management'
            ])->value('value') ?? '';
            $config = json_decode($config, true);
            $param['type'] = $config['type'];
            switch ($config['type']) {
                case 1:
                    //非学院
                    $this->validate($param, [
                        'name|部门名称'  =>  'require',
                    ]);
                    if ($this->mode->where([
                        ['unit_id', '=', $this->userData['unit_id']],
                        ['type', '=', $param['type']],
                        ['pid', '=', $param['pid']??0],
                        ['name', '=', $param['name']],
                    ])->value('id')) {
                        throw new \Exception('部门名称不可重复！');
                    }
                    break;
                case 2:
                    //学院制
                    $this->validate($param, [
                        'name|部门名称'  =>  'require',
                        'mode|学制模板' =>  'require',
//                        'stage|学制阶段' =>  'require',
                    ]);
                    if ($this->mode->where([
                        ['unit_id', '=', $this->userData['unit_id']],
                        ['type', '=', $param['type']],
                        ['pid', '=', $param['pid']??0],
                        ['name', '=', $param['name']],
                    ])->value('id')) {
                        throw new \Exception('部门名称不可重复！');
                    }
                    break;
                default:
                    throw new \Exception('系统错误！');
            }
            if (!empty($param['pid'])) {
                $pid = $this->mode->find($param['pid']);
                if ($pid['level'] > 9) throw new \Exception('层级不能超过十级');
                $level = $pid['level'] + 1;
                //验证：如果是否学院制，第三层级（班级）班级编号必填，且单位内不能重复
                if ($level == 3 && empty($param['number']) && $param['type'] == 2) throw new \Exception('缺少班级编号！');
                $number = $this->mode->where([
                    ['unit_id','=', $this->userData['unit_id']],
                    ['pid','=',$param['pid']],
                ])->column('number');
                if (!empty($param['number']) && count($number) > 0 && in_array($param['number'], $number)) throw new \Exception('班级编号已存在！');
                $param['level'] = $level;
            } else {
                $param['level'] = 1;
            }
            $param['unit_id'] = $this->userData['unit_id'];
            $param['time'] = time();
            $this->mode->insert($param);
            return success([], '添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function update(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'department_management'
            ])->value('value') ?? '';
            $config = json_decode($config, true);
            $param['type'] = $config['type'];
            switch ($config['type']) {
                case 1:
                    //非学院
                    $this->validate($param, [
                        'name|部门名称'  =>  'require',
                    ]);
                    $id = $this->mode->where([
                        ['unit_id', '=', $this->userData['unit_id']],
                        ['name', '=', $param['name']],
                        ['type', '=', $param['type']],
                    ])->value('id');
                    if ($id && $id != $info['id']) {
                        throw new \Exception('部门名称不可重复！');
                    }
                    break;
                case 2:
                    //学院制
                    $this->validate($param, [
                        'name|部门名称'  =>  'require',
                        'mode|学制模板' =>  'require',
//                        'stage|学制阶段' =>  'require',
                    ]);
                    $id = $this->mode->where([
                        ['unit_id', '=', $this->userData['unit_id']],
                        ['name', '=', $param['name']],
                        ['type', '=', $param['type']],
                        ['mode', '=', $param['mode']],
                        ['stage', '=', $param['stage']??0],
                    ])->value('id');
                    if ($id && $id != $info['id']) {
                        throw new \Exception('部门名称不可重复！');
                    }
                    break;
                default:
                    throw new \Exception('系统错误！');
            }
            $info->save($param);
            return success([], '更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function del(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($info['type'] == 2 && $info['level'] == 2) throw new \Exception('学院制二级部门不可单独删除！');
            $data = $this->mode->field('id,pid')->where('unit_id','=',$this->userData['unit_id'])->select()->toArray();
            $ids = getAllLowerLevelId($data,$param['id']);
            $ids[] = $param['id'];
            $UserModel = new UserModel();
            if ($UserModel->where('department_id', 'in', $ids)->value('id')) throw new \Exception('当前部门或下属部门内存在用户无法删除！');
            $this->mode->where('id', 'in', $ids)->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            $departmentAdmin = new DepartmentAdminModel();
            $departmentAdmin->where('department_id', 'in', $ids)->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            $this->mode->commit();
            return success([], '删除成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 添加推送消息
     * @return false|string
     */
    public function allSendMessage(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'department_ids|接收对象' =>  'require',
                'channel|发送渠道' =>  'require',
                'content|消息内容' =>  'require',
                'is_timing|是否定时' =>  'require'
            ]);
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            $PushMessageModel = new PushMessageModel();
            $PushMessageModel->insert($param);
//            $Task = new Task();
//            $Task->SendMessage($param);
            return success([], '添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 指定管理员
     * @return false|string
     */
    public function updateAdmin(): bool|string
    {
        $DepartmentAdmin = new DepartmentAdminModel();
        $DepartmentAdmin->startTrans();
        try {
            $param = $this->request->param();
            $DepartmentAdmin->where('department_id', '=', $param['id'])->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            if (!empty($param['admin'])) {
                $adminData = [];
                foreach ($param['admin'] as $item) {
                    $adminData[] = [
                        'department_id' => $param['id'],
                        'uid' => $item,
                        'time' => time()
                    ];
                }
                $DepartmentAdmin->insertAll($adminData);
            }
            $DepartmentAdmin->commit();
            return success([], '更新成功！');
        } catch (\Exception $e) {
            $DepartmentAdmin->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 获取指定管理员信息
     * @return bool|string
     */
    public function getAdmin(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $DepartmentAdmin = new DepartmentAdminModel();
            $list = $DepartmentAdmin->field('id,uid')
                ->where('department_id', '=', $id)->with('userName')->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 部门选择器
     * @return false|string
     */
    public function departmentSelector(): bool|string
    {
        try {
            $level = $this->request->param('level');
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->field('id,name,mode,stage,number')
                ->with('departmentLevel')
                ->where([
                    'unit_id' => $this->userData['unit_id'],
                    'level' => $level
                ])->select()->toArray();
            foreach ($data as &$item) {
                $item['level_rules'] = isset($item['level_rules']) ? json_decode($item['level_rules'], true) : [];
                $item['stage_name'] = $item['level_rules'][$item['stage']] ?? '';
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 推送消息
     * @param Websocket $websocket
     * @return bool|string
     */
    public function PushMessage(Websocket $websocket): bool|string
    {
        $PushMessageModel = new PushMessageModel();
        $PushMessageModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'department_id|部门' => 'require',
                'content|内容' => 'require',
                'is_time|时间' => 'require',
                'channel|推送渠道' => 'require',
            ]);
            $time = time();
            if (!empty($param['time'])){
                $remaining_time = intval($param['time']) - $time;
            }else{
                $remaining_time = 0;
            }
            //系统日志
            $LogModel = new LogModel();
            $LogModel->insert([
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],
                'type' => 1,
                'ip' => (string) $this->getIp(),
                'behavior' => '推送即时消息',
                'status' => 1,
                'ua' => (string) $this->request->server('HTTP_USER_AGENT')??'',
                'time' => time()
            ]);
            //推送socket消息
            $socketServer = new Server();
            if (!$param['is_time'] || $remaining_time <= 0) {
                $PushMessageModel->insert([
                    'unit_id' => $this->userData['unit_id'],
                    'uid' => $this->userData['id'],
                    'department_id' => implode(',', $param['department_id']),
                    'channel' => implode(',', $param['channel']),
                    'content' => $param['content'],
                    'is_time' => $param['is_time'],
                    'send_time' => $param['send_time'] ?? 0,
                    'status' => 1,
                    'time' => $time,
                ]);
                $UserModel = new UserModel();
                $MessageModel = new MessageModel();
                $uids = $UserModel->where([
                    ['department_id', 'in', $param['department_id']],
                    ['role_mode','=',3]
                ])->column('id');
                $fd = $socketServer->uidGetFd($uids);
                $socketSendData = [
                    'type' => 'message',
                    'content' => [
                        'type' => 23,
                        'title' => '系统推送',
                        'content' => $param['content'],
                        'img' => match (23) {
                            3, 4, 5, 7, 8, 9, 10 => '/icon_task/202411/07_1730960087672c5ad715646.png',//测评任务消息
                            6, 11, 1, 2, 14, 15, 16, 23 => '/icon_task/202411/07_1730960430672c5c2ee2c98.png',//预警报告消息-系统通知-公告-危机干预
                            17 => '/icon_task/202411/07_1730944047672c1c2fd624c.png',//预约咨询消息
                            22 => '/icon_task/202411/07_1730941588672c1294c2e1e.png',//物联网消息
                        },
                        'time' => time()
                    ]
                ];
                $MessageData = [];
                foreach ($uids as $uid) {
                    $MessageData[] = [
                        'uid' => $uid,
                        'type' => 23,
                        'title' => '系统推送',
                        'content' => $param['content'],
                        'time' => time()
                    ];
                }
                $MessageModel->insertAll($MessageData);
            } else {
                $id = $PushMessageModel->insertGetId([
                    'unit_id' => $this->userData['unit_id'],
                    'uid' => $this->userData['id'],
                    'department_id' => implode(',', $param['department_id']),
                    'channel' => implode(',', $param['channel']),
                    'content' => $param['content'],
                    'is_time' => $param['is_time'],
                    'send_time' => $param['send_time'] ?? 0,
                    'status' => 0,
                    'time' => $time,
                ]);
                if (!Queue::later($remaining_time, \app\job\CronJob::class, [
                    'method' => 'PushMessage',
                    'data' => [
                        'message_id' => $id
                    ],
                ], 'CronJob'))
                    throw new \Exception('队列创建失败！');
            }
            $PushMessageModel->commit();
            if (!empty($fd) && !empty($socketSendData)) {
                $socketServer->push($fd, json_encode($socketSendData), $websocket);
            }
            return success([], '推送成功！');
        } catch (\Exception $e) {
            $PushMessageModel->rollback();
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 推送历史记录
     * @return bool|string
     */
    public function PushMessageList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require'
            ]);
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $PushMessageModel = new PushMessageModel();
            $data = $PushMessageModel->where($where)->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                $item['department_id'] = explode(',', $item['department_id']);
                $item['channel'] = explode(',', $item['channel']);
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 推送历史记录-删除
     * @return bool|string
     */
    public function PushMessageDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $PushMessageModel = new PushMessageModel();
            $info = $PushMessageModel->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info->is_del = 1;
            $info->del_time = time();
            $info->save();
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

}
